<template>
  <view class="search-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-content">
        <view class="back-btn" @click="goBack">
          <text class="back-icon">←</text>
        </view>
        <text class="navbar-title">搜索</text>
        <view class="navbar-placeholder"></view>
      </view>
    </view>

    <!-- 搜索框区域 -->
    <view class="search-header">
      <view class="search-input-wrapper">
        <view class="search-icon">🔍</view>
        <input
          class="search-input"
          type="text"
          placeholder="搜索动态内容..."
          v-model="searchKeyword"
          @input="onSearchInput"
          @confirm="performSearch"
          confirm-type="search"
          focus
        />
        <view v-if="searchKeyword" class="clear-btn" @click="clearSearch">
          ✕
        </view>
      </view>
      <view class="search-btn" @click="performSearch">搜索</view>
    </view>

    <!-- 搜索历史 -->
    <view
      v-if="!hasSearched && searchHistory.length > 0"
      class="search-history"
    >
      <view class="history-header">
        <text class="history-title">搜索历史</text>
        <view class="clear-history-btn" @click="clearHistory">
          <text class="clear-text">清空</text>
        </view>
      </view>
      <view class="history-tags">
        <view
          v-for="(item, index) in searchHistory"
          :key="index"
          class="history-tag"
          @click="searchFromHistory(item)"
        >
          {{ item }}
        </view>
      </view>
    </view>

    <!-- 热门搜索 -->
    <view v-if="!hasSearched" class="hot-search">
      <view class="hot-search-title">热门搜索</view>
      <view class="hot-search-tags">
        <view
          v-for="(item, index) in hotSearchKeywords"
          :key="index"
          class="hot-search-tag"
          @click="searchFromHistory(item)"
        >
          {{ item }}
        </view>
      </view>
    </view>

    <!-- 搜索结果 -->
    <view v-if="hasSearched" class="search-results">
      <view class="result-header">
        <text class="result-count">找到 {{ searchResults.length }} 条结果</text>
      </view>

      <!-- 搜索结果列表 -->
      <view v-if="searchResults.length > 0" class="result-list">
        <DynamicsList
          :dynamicsList="searchResults"
          :loading="searching"
          :noMore="true"
          :likedItems="likedItems"
          @likeClick="handleLike"
        />
      </view>

      <!-- 无搜索结果 -->
      <view v-else-if="!searching" class="no-results">
        <view class="no-results-icon">😔</view>
        <text class="no-results-text">没有找到相关动态</text>
        <text class="no-results-tip">试试其他关键词吧</text>
      </view>

      <!-- 搜索中loading -->
      <view v-if="searching" class="searching-loading">
        <view class="loading-icon">🔍</view>
        <text class="loading-text">搜索中...</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import axios from "axios";
// @ts-ignore
import DynamicsList from "../zujian/dynamics_list.vue";

// 声明uni全局对象
declare const uni: any;

// 定义类型接口
interface Attachment {
  url: string;
  type?: string;
  name?: string;
  poster?: string;
}

interface DynamicItem {
  id: number;
  username: string;
  avatar: string;
  time: string;
  content: string;
  categoryId: string;
  categoryName: string;
  likes: number;
  comments: number;
  favorites: number;
  isHot: boolean;
  attachments?: Attachment[];
}

// 响应式数据
const searchKeyword = ref<string>("");
const searchResults = ref<DynamicItem[]>([]);
const searching = ref<boolean>(false);
const hasSearched = ref<boolean>(false);
const likedItems = ref<Set<string | number>>(new Set());

// 搜索历史
const searchHistory = ref<string[]>([]);
const hotSearchKeywords = ref<string[]>([
  "找对象",
  "表白",
  "吐槽",
  "求助",
  "兼职",
  "失物",
  "租房",
  "二手",
]);

// 方法
const onSearchInput = () => {
  // 可以在这里添加实时搜索功能
};

const performSearch = async () => {
  if (!searchKeyword.value.trim()) {
    uni.showToast({
      title: "请输入搜索关键词",
      icon: "none",
    });
    return;
  }

  searching.value = true;
  hasSearched.value = true;

  try {
    // 调用后端搜索API
    const response = await axios.get("/h5api/jjx/search", {
      params: {
        keyword: searchKeyword.value.trim(),
        page: 1,
        limit: 20,
      },
    });

    if (response.status === 200 && response.data.success) {
      const essayData = response.data.data || [];

      // 将essay数据转换为前端显示格式
      const searchData = essayData.map((essay: any, index: number) => {
        return {
          id: essay._id || index + 1,
          username: essay.anonymity
            ? "匿名用户"
            : essay.author?.name || "匿名用户",
          avatar:
            "",
          time: essay.createdata
            ? new Date(essay.createdata)
                .toLocaleString("zh-CN", {
                  year: "numeric",
                  month: "2-digit",
                  day: "2-digit",
                  hour: "2-digit",
                  minute: "2-digit",
                })
                .replace(/\//g, "-")
            : new Date()
                .toLocaleString("zh-CN", {
                  year: "numeric",
                  month: "2-digit",
                  day: "2-digit",
                  hour: "2-digit",
                  minute: "2-digit",
                })
                .replace(/\//g, "-"),
          content: essay.context || "暂无内容",
          categoryId: essay.topic?.[0] || "all",
          categoryName: essay.topic?.[0] || "全部",
          likes: essay.likes?.length || 0,
          comments: essay.comments || 0,
          favorites: essay.views || 0,
          isHot: (essay.views || 0) > 10 || (essay.likes?.length || 0) > 3,
          // 将后端的img字段转换为前端的attachments格式
          attachments:
            essay.img?.map((imgUrl: string) => ({
              url: imgUrl,
              type: "image",
              name: "图片",
            })) || [],
        };
      });

      searchResults.value = searchData;

      // 保存搜索历史
      saveSearchHistory(searchKeyword.value.trim());
    } else {
      uni.showToast({
        title: "搜索失败，请重试",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("搜索失败:", error);
    uni.showToast({
      title: "网络错误，请检查网络连接",
      icon: "none",
    });
  } finally {
    searching.value = false;
  }
};

const clearSearch = () => {
  searchKeyword.value = "";
  searchResults.value = [];
  hasSearched.value = false;
};

const searchFromHistory = (keyword: string) => {
  searchKeyword.value = keyword;
  performSearch();
};

const saveSearchHistory = (keyword: string) => {
  // 移除重复项
  const history = searchHistory.value.filter((item) => item !== keyword);
  // 添加到最前面
  history.unshift(keyword);
  // 最多保存10条历史记录
  searchHistory.value = history.slice(0, 10);

  // 保存到本地存储
  uni.setStorageSync("searchHistory", searchHistory.value);
};

const clearHistory = () => {
  searchHistory.value = [];
  uni.removeStorageSync("searchHistory");
  uni.showToast({
    title: "已清空搜索历史",
    icon: "none",
  });
};

const goBack = () => {
  uni.navigateBack({
    delta: 1,
  });
};

const handleLike = async (item: DynamicItem) => {
  try {
    const userId = "user123"; // 实际项目中应该从用户状态获取

    const response = await axios.post(`/h5api/jjx/likeessay/${item.id}`, {
      userId: userId,
    });

    if (response.status === 200 && response.data.success) {
      // 更新本地数据
      const targetItem = searchResults.value.find((d) => d.id === item.id);
      if (targetItem) {
        targetItem.likes = response.data.data.likes;
      }

      // 更新点赞状态
      if (likedItems.value.has(item.id)) {
        likedItems.value.delete(item.id);
      } else {
        likedItems.value.add(item.id);
      }

      uni.showToast({
        title: response.data.message,
        icon: "success",
      });
    }
  } catch (error) {
    console.error("点赞失败:", error);
    uni.showToast({
      title: "点赞失败，请重试",
      icon: "none",
    });
  }
};

// 生命周期
onMounted(() => {
  // 加载搜索历史
  try {
    const history = uni.getStorageSync("searchHistory");
    if (history) {
      searchHistory.value = history;
    }
  } catch (error) {
    console.error("加载搜索历史失败:", error);
  }
});
</script>

<style lang="scss" scoped>
.search-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 自定义导航栏 */
.custom-navbar {
  background: linear-gradient(135deg, #ff6e26, #ff8c42);
  padding-top: var(--status-bar-height);
  box-shadow: 0 2rpx 8rpx rgba(255, 110, 38, 0.2);
}

.navbar-content {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20rpx;
  position: relative;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  transition: all 0.2s ease;

  &:active {
    transform: scale(0.9);
    background-color: rgba(255, 255, 255, 0.3);
  }
}

.back-icon {
  font-size: 32rpx;
  color: white;
  font-weight: bold;
}

.navbar-title {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  font-size: 32rpx;
  font-weight: 600;
  color: white;
  text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
}

.navbar-placeholder {
  width: 60rpx;
  height: 60rpx;
}

/* 搜索框区域 */
.search-header {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.search-input-wrapper {
  flex: 1;
  position: relative;
  background-color: #f8f8f8;
  border-radius: 25rpx;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  margin-right: 20rpx;
  border: 2rpx solid transparent;
  transition: all 0.3s ease;

  &:focus-within {
    border-color: #ff6e26;
    background-color: #fff;
    box-shadow: 0 0 0 4rpx rgba(255, 110, 38, 0.1);
  }
}

.search-icon {
  font-size: 28rpx;
  color: #999;
  margin-right: 12rpx;
}

.search-input {
  flex: 1;
  height: 70rpx;
  font-size: 28rpx;
  color: #333;
  background: transparent;
  border: none;
  outline: none;

  &::placeholder {
    color: #999;
  }
}

.clear-btn {
  width: 32rpx;
  height: 32rpx;
  background-color: #ccc;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20rpx;
  color: #fff;
  margin-left: 10rpx;
  transition: all 0.2s ease;

  &:active {
    transform: scale(0.9);
    background-color: #999;
  }
}

.search-btn {
  background: linear-gradient(135deg, #ff6e26, #ff8c42);
  color: white;
  padding: 20rpx 30rpx;
  border-radius: 25rpx;
  font-size: 28rpx;
  font-weight: 600;
  transition: all 0.2s ease;

  &:active {
    transform: scale(0.95);
    box-shadow: 0 4rpx 12rpx rgba(255, 110, 38, 0.3);
  }
}

/* 搜索历史 */
.search-history {
  background-color: #fff;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.history-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
}

.clear-history-btn {
  padding: 8rpx 16rpx;
  background-color: #f0f0f0;
  border-radius: 16rpx;
  transition: all 0.2s ease;

  &:active {
    background-color: #e0e0e0;
    transform: scale(0.95);
  }
}

.clear-text {
  font-size: 24rpx;
  color: #666;
}

.history-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.history-tag {
  background-color: #f8f8f8;
  color: #666;
  padding: 12rpx 20rpx;
  border-radius: 20rpx;
  font-size: 26rpx;
  transition: all 0.2s ease;

  &:active {
    background-color: #ff6e26;
    color: white;
    transform: scale(0.95);
  }
}

/* 热门搜索 */
.hot-search {
  background-color: #fff;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.hot-search-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;

  &::before {
    content: "🔥";
    margin-right: 8rpx;
  }
}

.hot-search-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.hot-search-tag {
  background: linear-gradient(135deg, #ffe5d9, #fff0e6);
  color: #ff6e26;
  padding: 12rpx 20rpx;
  border-radius: 20rpx;
  font-size: 26rpx;
  border: 1rpx solid rgba(255, 110, 38, 0.2);
  transition: all 0.2s ease;

  &:active {
    background: linear-gradient(135deg, #ff6e26, #ff8c42);
    color: white;
    transform: scale(0.95);
  }
}

/* 搜索结果 */
.search-results {
  margin-top: 20rpx;
}

.result-header {
  background-color: #fff;
  padding: 20rpx 30rpx;
  margin: 0 20rpx 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.result-count {
  font-size: 28rpx;
  color: #666;
}

.result-list {
  margin: 0 20rpx;
}

/* 无搜索结果 */
.no-results {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 20rpx;
  background-color: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.no-results-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
  opacity: 0.6;
}

.no-results-text {
  font-size: 32rpx;
  color: #666;
  margin-bottom: 10rpx;
  font-weight: 500;
}

.no-results-tip {
  font-size: 26rpx;
  color: #999;
}

/* 搜索中loading */
.searching-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 20rpx;
}

.loading-icon {
  font-size: 48rpx;
  animation: rotate 1s linear infinite;
  margin-bottom: 20rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 响应式适配 */
@media screen and (max-width: 750rpx) {
  .navbar-content {
    height: 80rpx;
    padding: 0 15rpx;
  }

  .back-btn {
    width: 50rpx;
    height: 50rpx;
  }

  .back-icon {
    font-size: 28rpx;
  }

  .navbar-title {
    font-size: 28rpx;
  }

  .navbar-placeholder {
    width: 50rpx;
    height: 50rpx;
  }

  .search-header {
    padding: 15rpx;
  }

  .search-input-wrapper {
    margin-right: 15rpx;
  }

  .search-input {
    height: 60rpx;
    font-size: 26rpx;
  }

  .search-btn {
    padding: 15rpx 25rpx;
    font-size: 26rpx;
  }

  .search-history,
  .hot-search {
    margin: 15rpx;
    padding: 25rpx;
  }
}
</style>